package com.jadesoft.listener;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import org.apache.log4j.Logger;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.springframework.util.Assert;

import com.jadesoft.common.service.PaginationService;
import com.jadesoft.stock.FetionHelper;
import com.jadesoft.stock.entity.WeatherInfo;

public class WeatherTask extends TimerTask {
	private Logger logger = Logger.getLogger(WeatherTask.class);
	private PaginationService persistence = new PaginationService();
	private Map<String, WeatherInfo[]> wthInfoMap = new HashMap<String, WeatherInfo[]>();

	@SuppressWarnings({ "unchecked" })
	public void run() {
		logger.debug(Calendar.getInstance());

		this.getAndSaveData();

		FetionHelper.sendMsg(this.createMsgList());

		this.wthInfoMap.clear();
	}

	public void getAndSaveData() {
		List<Object[]> citys = this.loadSubscriptedCities();
		List<WeatherInfo> todayInfoList = new ArrayList<WeatherInfo>();
//		Properties prop = System.getProperties();
//		prop.setProperty("http.proxyHost", "128.96.172.23");
//		prop.setProperty("http.proxyPort", "808");
		try {
			Date date = new Date();
			TagNameFilter dateFilter = new TagNameFilter("DD");
			TagNameFilter wthFilter = new TagNameFilter("DT");
			for (Object[] city : citys) {
				String code = city[0].toString();
				String name = city[1].toString();
				//特殊处理的城市//
				
				String url = "http://wap.weather.com.cn/wap/weather/" + this.transCode(code)
						+ ".shtml";
				logger.info(url);
				Parser parser = new Parser(
						(HttpURLConnection) (new URL(url)).openConnection());
				Parser parser_2 = new Parser(
						(HttpURLConnection) (new URL(url)).openConnection());

				WeatherInfo today = new WeatherInfo(code,name, date);
				WeatherInfo tomorrow = new WeatherInfo(code,name);
				WeatherInfo aftTmr = new WeatherInfo(code,name);
				NodeList nodes = parser.extractAllNodesThatMatch(dateFilter);
				today.setContent(nodes.elementAt(0).toPlainTextString() + ",");
				tomorrow.setContent(nodes.elementAt(1).toPlainTextString()
						+ ",");
				aftTmr.setContent(nodes.elementAt(2).toPlainTextString() + ",");

				nodes = parser_2.extractAllNodesThatMatch(wthFilter);
				today.addContent(nodes.elementAt(0).toPlainTextString()
						.replace("&nbsp;", ","));
				tomorrow.addContent(nodes.elementAt(1).toPlainTextString()
						.replace("&nbsp;", ","));
				aftTmr.addContent(nodes.elementAt(2).toPlainTextString()
						.replace("&nbsp;", ","));

				todayInfoList.add(today);
				wthInfoMap.put(code, new WeatherInfo[] { today, tomorrow,
						aftTmr });
			}
			persistence.saveObjs(todayInfoList.toArray());
			todayInfoList.clear();
		} catch (Exception e) {
			logger.error(e);
		}

	}

	/**
	 * query subscript data ,create content
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List createMsgList() {
		List result = new ArrayList();
		String sql = " SELECT a.mobile_no,b.codes"
				+ "	 FROM (SELECT user_id,GROUP_CONCAT(city_code) AS codes  "
				+ "			FROM weather_subscript GROUP BY user_id) AS b,"
				+ " user AS a WHERE a.id = b.user_id"
				+ " AND a.mobile_no IS NOT NULL";
		logger.debug(sql);
		List<Object[]> list = this.persistence.queryBySql(sql);
		String mobileNo = null;
		String content = null;
		for (int i = 0; i < list.size(); i++) {
			mobileNo = list.get(i)[0].toString();
			try {
				content = getContent(list.get(i)[1].toString().split(","));//捕获异常,可以继续发送其他的订阅
				result.add(new String[] { mobileNo, content });
			} catch (Exception e) {
				logger.error(e);
			}
	
		}
		return result;
	}

	public String getContent(String[] codes) {
		String content = "";
		for (String code : codes) {
			content += this.getText(code);
		}
		return content;
	}

	public String getText(String code) {
		 WeatherInfo[] wthInfos = this.wthInfoMap.get(code);
		 Assert.notEmpty(wthInfos,code+ ":不存在");
		 String txt = wthInfos[0].getCityName()+":";
		 txt+="今天"+wthInfos[0].getContent()+".";
		 txt+="明天"+wthInfos[1].getContent()+".";
//		 txt+="后天"+wthInfos[2].getContent()+".";//只发两天的数据
		logger.debug(txt.replace(" ",""));
		 return txt.replace(" ", "");
	}

	@SuppressWarnings("unchecked")
	public List<Object[]> loadSubscriptedCities() {
		String sql = "SELECT DISTINCT(city_code),city_name FROM weather_subscript";
		return  this.persistence.queryBySql(sql);
	}
	
	public static void main(String[] args) {
		WeatherTask task = new WeatherTask();
		task.run();
//		System.out.println(task.transCode("101010001"));
	}

	//处理特殊的CODE
	public String transCode(String code){
		//1直辖市 最后两位和倒数两位互换
		String[] zhixia = new String[]{"10101","10102","10103","10104"};
		for (String c : zhixia) {
			if(code.startsWith(c)){
				String c1 = code.substring(5, 7);
				String c2 = code.substring(7);
				code = code.substring(0,5)+c2+c1;
				return code;
			}
		}
		return code;
	}
	
}
